package com.jy.blog.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.jy.blog.dao.MessageDao;
import com.jy.blog.model.Message;
import com.jy.blog.utils.DBHelper;

public class MessageDaoImpl implements MessageDao{
	private Connection conn;
	private PreparedStatement pstm;
	private ResultSet rs;
	@Override
	public List<Message> selectAllMessage() {
		List<Message> list=new ArrayList<Message>();
		conn=DBHelper.getConnection();
		String sql="SELECT message_id,mess_content,mess_date,mess_title"
				+ " FROM message";
		try {
			pstm=conn.prepareStatement(sql);
			rs=pstm.executeQuery();
			while(rs.next()){
				Message message=new Message();
				message.setMessageId(rs.getInt(1));
				message.setMessContent(rs.getString(2));
				message.setMessDate(rs.getString(3));
				message.setMessTitle(rs.getString(4));
				list.add(message);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			DBHelper.closeAll(pstm, rs);
		}
		return list;
	}

	@Override
	public int del(int id) {
		int result=0;
		conn=DBHelper.getConnection();
		String sql="DELETE FROM message WHERE message_id=?";
		try {
			pstm=conn.prepareStatement(sql);
			pstm.setInt(1, id);
			result=pstm.executeUpdate();
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			DBHelper.closeAll(pstm, rs);
		}
		return result;
	}

	@Override
	public int add(Message message) {
		int result=0;
		conn=DBHelper.getConnection();
		String sql="INSERT INTO message  VALUES(NULL,?,?,?)";
		 try {
				pstm=conn.prepareStatement(sql);
				 pstm.setString(1,message.getMessContent());
				 pstm.setString(2, message.getMessTitle());
				 pstm.setString(3, message.getMessDate());
				 result=pstm.executeUpdate();
			 result=pstm.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			DBHelper.closeAll(pstm, rs);
		}
		return result;
	}

}
